import pymysql
from django.shortcuts import render
from loguru import logger
from rest_framework.request import Request
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters, status
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import Element
from datetime import datetime

from apps.TabletInfo.filters import TabletInfoFilter
from apps.TabletInfo.serializers import ReadTabletinfoSerializer, WriteTabletinfoSerializer
from op_drf.dj_utils import set_delete, create_by_serializer
from op_drf.response import SuccessResponse
from op_drf.viewsets import CustomModelViewSet, ReadOnlyModelViewSet
from apps.TabletInfo.models import TabletInfo

# Create your views here.

class TabletInfoView(CustomModelViewSet):
    """
    处方信息的CRUD
    """
    queryset = TabletInfo.objects.filter()
    serializer_class = ReadTabletinfoSerializer  # 序列化器
    update_serializer_class = WriteTabletinfoSerializer
    # 分页
    # pagination_class = Pagination
    # 筛选
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = TabletInfoFilter
    search_fields = ("id", )
    filter_fields = ("id", )
    ordering_fields = ("-id",)
    ordering = ["-id"]

    def create(self, request: Request, *args, **kwargs):
        logger.debug("前端传入的数据： %s" % request.data)
        logger.debug("请求携带的数据： %s" % kwargs)
        conn = pymysql.connect(
            host='127.0.0.1',  # 主机名
            port=3306,  # 端口号，MySQL默认为3306
            user='root',  # 用户名
            password='admin2014',  # 密码
            database='yicheng_xiangyangxing',  # 数据库名称
        )
        # 创建游标对象
        cursor = conn.cursor()
        # 执行 SQL 查询语句
        cursor.execute("SELECT * FROM xyx_tabletinfo")
        # 获取查询结果
        result = cursor.fetchall()

        n = 0
        for r in result:
            n += 1
            print(r)
            if n>10:
                break

        return SuccessResponse(status=status.HTTP_201_CREATED)